package com.demo.jianjunhuang.catimgwebview;

import android.content.Context;
import android.webkit.WebView;
import android.widget.Toast;

/**
 * @author jianjunhuang.me@foxmail.com
 *         create on 2017/7/11.
 */

public class JavascriptInterface {

    private Context context;

    private WebView webView;

    public JavascriptInterface(WebView webView, Context context) {
        this.context = context;
        this.webView = webView;
    }

    private String imgUrl;

    @android.webkit.JavascriptInterface
    public void onImageUrl(final String imgUrl, String id) {
        Toast.makeText(context, imgUrl + " " + id, Toast.LENGTH_SHORT).show();
        webView.post(new Runnable() {
            @Override
            public void run() {
                showImage(webView, imgUrl);
            }
        });
    }

    public String getImgUrl() {
        return imgUrl;
    }

    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }

    public void showImage(WebView webView, String imgUrl) {
        String url = "javascript: (function() {" +
                "  var img = document.getElementById(\"" + imgUrl + "\");" +
//                "  if (img != null) {" +
                "    img.src = img.id;" +
//                "  }" +
                "})()";
        webView.loadUrl(url);
    }
}
